import { initGlobalState } from 'qiankun';

const initialState = {
  triggerChildEvent: null,
};

export const actions = initGlobalState(initialState);

export const sendToSubApp = (data) => {
  actions.setGlobalState({
    triggerChildEvent: data,
  });
};

export function sendToChildWithAck(event) {
  return new Promise((resolve, reject) => {
    const callbackId = 'cb_' + Date.now();

    // 监听子应用回应
    const handler = (e) => {
      if (e.data?.type === 'CHILD_ACK' && e.data?.callbackId === callbackId) {
        window.removeEventListener('message', handler);
        resolve(e.data?.result);
      }
    };
    window.addEventListener('message', handler);

    // 发送事件
    const payload = { ...event, callbackId };
    sendToSubApp(payload);

    // 超时防止永久卡死
    setTimeout(() => {
      window.removeEventListener('message', handler);
      reject(new Error('子应用未响应'));
    }, 5000);
  });
}
